package Tables;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import TableAdditions.CustomerTableAddition;
import TableAdditions.CustomerUnitPriceTableAddition;
import Utility.Supplier;
import TableAdditions.SupplierTableAddition;
import TableAdditions.main;
import TableEditions.SupplierTableEdition;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class SupplierTableInterface extends JPanel implements ActionListener  {
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    JButton supplierAddButton=new JButton("Yeni");
    JButton supplierDeleteButton=new JButton("Sil");
    JButton supplierEditButton=new JButton("Düzenle");
    
    int counter=0;
    Supplier[] suppliers;
    String supplierName="";
    String supplierCode="";
    int selectedRow=-1;
    
    final String[] newData=new String[4]; 
    SupplierTableAddition additive;
    SupplierTableEdition edit;;
    
    public SupplierTableInterface() {
    	
    	//super(new GridBagLayout());
 
        String[] columnNames = {"Tedarikçi Kodu",
                                "Tedarikçi Adı","Tedarikçi Adresi","Tedarikçi Telefonu"};
	 	
	
  
        for(int i=0;i<columnNames.length;i++)
        	model.addColumn(columnNames[i]);	//add columns
        
        
        addNewItem();
        
        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);
      //Add the scroll pane to this panel.
        add(scrollPane);
        
        table.addMouseListener(new MouseAdapter() {
			
			
			@Override
			public void mouseClicked(MouseEvent arg0) {
				// TODO Auto-generated method stub
				 if (table.getColumnSelectionAllowed()
		                    && !table.getRowSelectionAllowed()) {
					  
		                System.out.println("11111111111111");
		                // Column selection is enabled
		                // Get the indices of the selected columns
		                int[] vColIndices = table.getSelectedColumns();
		            } else if (!table.getColumnSelectionAllowed()
		                    && table.getRowSelectionAllowed()) {
		            	// System.out.println("222222222222");
		            	 selectedRow=table.getSelectedRow(); 
		            	 
		            	 if(selectedRow>-1){
		            		 supplierName=suppliers[selectedRow].getSupplierName();
		            		 supplierCode=suppliers[selectedRow].getSupplierCode();
		 
		            	 }
		            	 //System.out.println("selectedCustomer= "+customerNames[selectedRow]);
		                // Row selection is enabled
		                // Get the indices of the selected rows
		                int[] rowIndices = table.getSelectedRows();
		            } else if (table.getCellSelectionEnabled()) {
		                // Individual cell selection is enabled
		            	System.out.println("333333333333");

		                // In SINGLE_SELECTION mode, the selected cell can be retrieved using
		            	table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		                int rowIndex = table.getSelectedRow();
		                int colIndex = table.getSelectedColumn();
		              

		                // In the other modes, the set of selected cells can be retrieved using
		                table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		                table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

		                // Get the min and max ranges of selected cells
		                int rowIndexStart = table.getSelectedRow();
		                int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
		                int colIndexStart = table.getSelectedColumn();
		                int colIndexEnd = table.getColumnModel().getSelectionModel()
		                    .getMaxSelectionIndex();

		                // Check each cell in the range
		                for (int r=rowIndexStart; r<=rowIndexEnd; r++) {
		                    for (int c=colIndexStart; c<=colIndexEnd; c++) {
		                        if (table.isCellSelected(r, c)) {
		                        	System.out.println("4444444444444");
		                            // cell is selected
		                        }
		                    }
		                }
		            }
				
			}
		});
        
        
        
        
        
        supplierAddButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				additive=new SupplierTableAddition(SupplierTableInterface.this);

				
			}
			
			
		});
        
        supplierEditButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if(selectedRow>-1){
					edit=new SupplierTableEdition(SupplierTableInterface.this,suppliers[selectedRow]);
				}

				
			}
			
			
		});

        
        
        supplierDeleteButton.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				//additive=new CustomerUnitPriceTableAddition(CustomerUnitPriceTableInterface.this);
				if(selectedRow!=-1){
					System.out.println("Delete supplier");
					
					Connection con = null;
			        Statement st = null;
			        ResultSet rs = null;

			        String url = "jdbc:mysql://localhost:3306/mydb";
			        String user = "root";
			        String password = "qweasdzxc";
			        Object[][] mydata=null;
			        try {
			            con = (Connection) DriverManager.getConnection(url, user, password);
			            st = (Statement) con.createStatement();
			            st.executeUpdate("UPDATE supplier set activity='0' WHERE supplier_name='"+supplierName+"'" +
			            		"and supplier_code='"+supplierCode+"' ");
			            
			            addNewItem();
			           
			            
			            con.close();
			            
			            
			        } catch (SQLException ex) {
			            Logger lgr = Logger.getLogger(main.class.getName());
			            lgr.log(Level.SEVERE, ex.getMessage(), ex);

			        } finally {
			            try {
			                if (rs != null) {
			                    rs.close();
			                }
			                if (st != null) {
			                    st.close();
			                }
			                if (con != null) {
			                    con.close();
			                }

			            } catch (SQLException ex) {
			                Logger lgr = Logger.getLogger(main.class.getName());
			                lgr.log(Level.WARNING, ex.getMessage(), ex);
			            }
			        }
					/////////////////////////////////////////
				}
				
			}
			
			
		});
        
        
        addItem(supplierAddButton,0,1,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        addItem(supplierDeleteButton,0,2,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        addItem(supplierEditButton,0,3,1,1,GridBagConstraints.CENTER);//call the addItem method and add in panel
        
       
       
    }
    public void addNewItem(){
  		deleteAllRows(model);
  		
  		Connection con = null;
        Statement st = null;
        ResultSet rs = null;

        String url = "jdbc:mysql://localhost:3306/mydb";
        String user = "root";
        String password = "qweasdzxc";
        Object[][] mydata=null;
        try {
            con = (Connection) DriverManager.getConnection(url, user, password);
            st = (Statement) con.createStatement();
            rs=st.executeQuery("SELECT * from supplier WHERE activity='1' order by supplier_name");
            int i=0;
            counter=0;
            while(rs.next())
            	++counter;
            
           System.out.println("supplier counter!!!!!!!!!!!!!!= "+counter);
            
            mydata=new Object[counter][4];
            suppliers=new Supplier[counter];
            if(counter>0){
            		rs.first();
            		suppliers[i]=new Supplier();
            		mydata[i][0]=rs.getString("supplier_code");
            		suppliers[i].setSupplierCode(rs.getString("supplier_code"));
            		mydata[i][1]=rs.getString("supplier_name");
            		suppliers[i].setSupplierName(rs.getString("supplier_name"));
            		mydata[i][2]=rs.getString("supplier_address");
            		suppliers[i].setSupplierAddress(rs.getString("supplier_address"));
            		mydata[i][3]=rs.getString("supplier_phone");
            		suppliers[i].setSupplierPhone(rs.getString("supplier_phone"));
            		++i;
            		while(rs.next())
            		{
            				suppliers[i]=new Supplier();
            				suppliers[i]=new Supplier();
                    		mydata[i][0]=rs.getString("supplier_code");
                    		suppliers[i].setSupplierCode(rs.getString("supplier_code"));
                    		mydata[i][1]=rs.getString("supplier_name");
                    		suppliers[i].setSupplierName(rs.getString("supplier_name"));
                    		mydata[i][2]=rs.getString("supplier_address");
                    		suppliers[i].setSupplierAddress(rs.getString("supplier_address"));
                    		mydata[i][3]=rs.getString("supplier_phone");
                    		suppliers[i].setSupplierPhone(rs.getString("supplier_phone"));
                    		++i;
        
            		}
          
            
            	}   
            con.close();
        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(main.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);

        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                Logger lgr = Logger.getLogger(main.class.getName());
                lgr.log(Level.WARNING, ex.getMessage(), ex);
            }
        }
        
        table.setPreferredScrollableViewportSize(new Dimension(900, 600));
        table.setFillsViewportHeight(true);
 
        if(counter>0){   
        	for(int i=0;i<mydata.length;i++)
        		model.addRow(mydata[i]);
        }
    }
    
    public static void deleteAllRows(final DefaultTableModel model) {
	    for( int i = model.getRowCount() - 1; i >= 0; i-- ) {
	        model.removeRow(i);
	    }
	}
    
    
      
    
    /**
     * This method Add new row to the table
     */
    private void addTableByRow(Object[] yeni){
    	model.addRow(yeni);
   
    }

    /**
     *This method is good to use GridBagLayout simple
     * 
     */
    private void addItem(JComponent c, int x, int y, int width, int height, int align) {
        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = x;
        gc.gridy = y;
        gc.gridwidth = width;
        gc.gridheight = height;
        gc.weightx = 100.0;
        gc.weighty = 100.0;
        gc.insets = new Insets(5, 5, 5, 5);
        gc.anchor = align;
        gc.fill = GridBagConstraints.NONE;
        add(c, gc);
      }
	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}




